package mysql

import (
	"device-modbus/config"
	"device-modbus/internal/biz/query"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

var dsn = "go-device:6tDKYPyjJ6zyKXNy@tcp(localhost:3306)/go-device?charset=utf8&parseTime=True&loc=Local&timeout=30s&readTimeout=30s&writeTimeout=30s"

var DB *gorm.DB

func Init() {
	var err error
	if config.DeviceConfig.Mysql.Dsn != "" {
		dsn = config.DeviceConfig.Mysql.Dsn
	}
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: true,
		PrepareStmt:            true,
		Logger:                 logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	}
	db, _ := DB.DB()
	// 设置连接池参数
	db.SetMaxIdleConns(10)  // 最大空闲连接数
	db.SetMaxOpenConns(100) // 最大打开连接数
	db.SetConnMaxLifetime(time.Hour)
	db.SetConnMaxIdleTime(30 * time.Minute) // 最大空闲时间

	query.SetDefault(DB)
}
